package utfpr.si.servants;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Iterator;

import utfpr.si.interfaces.IntServidor;

public class ServidorServant extends UnicastRemoteObject implements IntServidor {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static HashMap<String, String> content = new HashMap<String,String>();
    public ServidorServant()throws RemoteException{
    	content.clear();
    }
	@Override
	public void updateTable(String target, double targetX, double targetY) throws RemoteException {
			if( content.containsKey(target) ){
				content.remove(target);
			}
			content.put(target, ""+targetX+":"+targetY);
	}
	@Override
	public String getAction(double posX, double posY) throws RemoteException {

		Iterator<String> it = content.keySet().iterator();
		double cX, cY, distance=0.0, degree=0.0,co,ca;
		while( it.hasNext() ){
			String key = it.next();
			String value = content.get( key );
			cX = Double.parseDouble(value.split(":")[0]);
			cY = Double.parseDouble(value.split(":")[1]);
			distance = Math.sqrt( Math.pow(cY-posY,2) + Math.pow(cX-posX,2) );
			co = (cY-posY);
			ca = (cX-posX);
			degree = Math.toDegrees( Math.atan( co/ca ) );
			if( co < 0 && ca < 0 ) degree += 180.0;
			else if( co < 0 ) degree += 360.0;
			else if( ca < 0 ) degree += 180.0;
			content.remove( key );
		}
		if( distance > 0.0 )
			return "AHEAD "+distance+" "+degree;
		else
			return "NONE";
	}
}